import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"
import { AuthEndpoints, baseUrl } from "@/app/consts"
import type {
  LoginInput,
  RegisterInput,
  UserResponse,
} from "@/app/auth/interfaces"
import type { User } from "@/app/user/interfaces"
import { setUser } from "@/app/user/userSlice"
import type {
  BaseQueryError,
  BaseQueryMeta,
} from "@reduxjs/toolkit/dist/query/baseQueryTypes"

// Building api for authentication
export const authApi = createApi({
  reducerPath: "authApi",
  baseQuery: fetchBaseQuery({ baseUrl }),
  // building the endpoints
  endpoints: builder => ({
    login: builder.mutation<UserResponse, LoginInput>({
      query: credentials => ({
        url: AuthEndpoints.Login,
        method: "POST",
        body: { ...credentials },
      }),
      transformResponse: (result: { jwt: string; user: User }) => ({
        user: result.user,
        jwt: result.jwt,
      }),
      async onQueryStarted(_args, { dispatch, queryFulfilled }) {
        const { data } = await queryFulfilled
        localStorage.setItem("token", data.jwt)
        dispatch(setUser(data.user))
      },
    }),
    register: builder.mutation<UserResponse, RegisterInput>({
      query: credentials => ({
        url: AuthEndpoints.Register,
        method: "POST",
        body: { ...credentials },
      }),
      transformResponse: (result: { jwt: string; user: User }) => ({
        user: result.user,
        jwt: result.jwt,
      }),
      async onQueryStarted(_args, { dispatch, queryFulfilled }) {
        const { data } = await queryFulfilled
        localStorage.setItem("token", data.jwt)
        dispatch(setUser(data.user))
      },
    }),
  }),
})

// Auto generated hook - starts with use & ends on mutation
export const { useLoginMutation, useRegisterMutation } = authApi
